const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('mime');
const chatServer = require('./lib/chat-server');

const cache = {};

function send404(res) {
  res.writeHead(404, { 'Content-Type': 'text/plain' });
  res.write('Error 404: resource not found.');
  res.end();
}

function sendFile(res, filePath, fileContent) {
  res.writeHead(200, { 'Content-Type': mime.getType(path.basename(filePath)) });
  res.end(fileContent);
}

function serverStatic(res, cache, absPath) {
  if (cache[absPath]) {
    sendFile(res, absPath, cache[absPath]);
  } else {
    fs.readFile(absPath, function (err, data) {
      if (err) {
        send404(res);
      } else {
        cache[absPath] = data;
        sendFile(res, absPath, data);
      }
    });
  }
}

const server = http.createServer(function (req, res) {
  let absPath = false;
  if (req.url == '/') {
    absPath = `${__dirname}\\public\\index.html`;
  } else {
    absPath = `${__dirname}\\public${req.url}`;
  }
  serverStatic(res, cache, absPath);
});
server.listen(3000, function () {
  console.log('Server listening on http://localhost:3000');
});

chatServer.listen(server);
